<template>
	<div class="node-wrap">
		<div class="node-wrap-box" @click="show">
			<div class="title" style="background: #ff943e;">
				<el-icon class="icon"><el-icon-user-filled /></el-icon>
				<span>{{ nodeConfig.nodeName }}</span>
				<el-icon class="close" @click.stop="delNode()"><el-icon-close /></el-icon>
			</div>
			<div class="content">
				<span v-if="toText(nodeConfig)">{{ toText(nodeConfig) }}</span>
				<span v-else class="placeholder">请选择</span>
			</div>
		</div>

		<div class="error_tip" v-if="nodeConfig.error">
			<el-icon>
				<Warning />
			</el-icon>
		</div>
		<add-node v-model="nodeConfig.childNode" :currentNode="nodeConfig"></add-node>
		<el-drawer title="审批人设置" v-model="drawer" destroy-on-close append-to-body :size="700" @close="save">
			<template #header>
				<div class="node-wrap-drawer__title">
					<label @click="editTitle" v-if="!isEditTitle">{{ form.nodeName }}<el-icon
							class="node-wrap-drawer__title-edit"><el-icon-edit /></el-icon></label>
					<el-input v-if="isEditTitle" ref="nodeTitle" v-model="form.nodeName" clearable @blur="saveTitle"
						@keyup.enter="saveTitle"></el-input>
				</div>
			</template>
			<el-container>
				<el-main style="padding:0 20px 20px 20px">
					<el-form label-position="top" class="formLabel">

						<el-form-item label="审批人员类型">
							<el-select v-model="form.assignedType" @change="typeChange">
								<el-option :value="1" label="指定成员"></el-option>
								<el-option :value="2" label="部门主管"></el-option>
								<el-option :value="3" label="角色"></el-option>
								<el-option :value="4" label="发起人自选"></el-option>
								<el-option :value="5" label="发起人自己"></el-option>
								<el-option :value="7" label="连续多级主管"></el-option>
								<el-option :value="8" label="表单人员"></el-option>
								<el-option :value="9" label="表单部门"></el-option>
								<el-option :value="10" label="指定部门主管"></el-option>
								<el-option :value="11" label="系统自动拒绝"></el-option>
							</el-select>
						</el-form-item>

						<el-form-item v-if="form.assignedType == 1" label="选择人员">
							<sc-table-select v-model="employeeList" :apiObj="apiObj" :fileName="employeeFileName"
								:table-width="700" multiple clearable collapse-tags collapse-tags-tooltip
								:props="tableProps" @change="employeeChange">
							</sc-table-select>
							<div class="tags-list">
								<el-tag v-for="(role, index) in employeeList" :key="role.id" type="info" closable
									@close="delEmployee(index)">{{ role.name }}</el-tag>
							</div>
						</el-form-item>

						<el-form-item v-if="form.assignedType == 2" label="指定主管">
							发起人的第 <el-input-number v-model="form.deptLeaderLevel" :min="1" /> 级主管
						</el-form-item>

						<el-form-item v-if="form.assignedType == 3" label="选择角色">
							<sc-table-select v-model="roleList" :apiObj="apiObj" :fileName="roleFileName" :table-width="700"
								multiple clearable collapse-tags collapse-tags-tooltip :props="tableProps"
								@change="roleChange">
							</sc-table-select>
							<div class="tags-list">
								<el-tag v-for="(role, index) in roleList" :key="role.id" type="info" closable
									@close="delRole(index)">{{ role.name }}</el-tag>
							</div>
						</el-form-item>

						<el-form-item v-if="form.assignedType == 4" label="选择方式">
							<el-radio-group v-model="form.multiple" class="ml-4">
								<el-radio :label="false" size="large">单选</el-radio>
								<el-radio :label="true" size="large">多选</el-radio>
							</el-radio-group>
						</el-form-item>

						<el-form-item v-if="form.assignedType == 7" label="连续主管审批终点">
							<p>直到发起人的第 <el-input-number v-model="form.deptLeaderLevel" :min="1" />
								级主管</p>
						</el-form-item>
						<el-form-item v-if="form.assignedType == 8" label="人员控件">
							<el-select v-model="formUserId" clearable placeholder="请选择审批表单">
								<el-option v-for="item in formUserList" :key="item.id" :label="item.name"
									:value="item.id" />
							</el-select>
						</el-form-item>
						<el-form-item v-if="form.assignedType == 9" label="部门控件">
							<el-row :gutter="30">
								<el-col :span="12">
									<el-select v-model="formDeptId" clearable placeholder="请选择审批表单">
										<el-option v-for="item in formDeptList" :key="item.id" :label="item.name"
											:value="item.id" />
									</el-select>
								</el-col>
								<el-col :span="12">
									<el-radio-group v-model="form.deptUserType" style="margin-top: -3px;">
										<el-radio label="allUser" size="large">部门人员</el-radio>
										<el-radio label="leader" size="large">部门主管</el-radio>
									</el-radio-group>
								</el-col>
							</el-row>
						</el-form-item>
						<el-form-item v-if="form.assignedType == 10" label="选择部门">
							<sc-table-select v-model="deptList" :apiObj="apiObj" :fileName="deptFileName" :table-width="700"
								multiple clearable collapse-tags collapse-tags-tooltip :props="tableProps"
								@change="deptChange">
							</sc-table-select>
							<div class="tags-list">
								<el-tag v-for="(role, index) in deptList" :key="role.id" type="info" closable
									@close="delDept(index)">{{ role.name }}</el-tag>
							</div>
						</el-form-item>

						<!-- <el-form-item label="">
							<el-checkbox v-model="form.termAuto" label="超时自动审批"></el-checkbox>
						</el-form-item>
						<template v-if="form.termAuto">
							<el-form-item label="审批期限（为 0 则不生效）">
								<el-input-number v-model="form.term" :min="0" /> 小时
							</el-form-item>
							<el-form-item label="审批期限超时后执行">
								<el-radio-group v-model="form.termMode">
									<el-radio :label="0">自动通过</el-radio>
									<el-radio :label="1">自动拒绝</el-radio>
								</el-radio-group>
							</el-form-item>
						</template> -->
						<el-form-item label="审批人为空时" v-if="form.assignedType !== 11">
							<el-radio-group v-model="form.nobody.handler">
								<el-radio label="TO_PASS" size="large">自动通过</el-radio>
								<el-radio label="TO_REFUSE" size="large">自动拒绝</el-radio>
								<el-radio label="TO_ADMIN" size="large">转交给管理员</el-radio>
								<el-radio label="TO_USER" size="large">指定人员</el-radio>
							</el-radio-group>
						</el-form-item>
						<el-form-item v-if="form.nobody.handler === 'TO_USER'" label="选择人员">
							<sc-table-select v-model="employeeList2" :apiObj="apiObj" :fileName="employeeFileName"
								:table-width="700" multiple clearable collapse-tags collapse-tags-tooltip
								:props="tableProps2" @change="employeeChange2">
							</sc-table-select>
						</el-form-item>
						<el-form-item label="多人审批时审批方式" v-if="form.assignedType !== 11 && form.assignedType !== 5">
							<el-radio-group v-model="form.multipleMode">
								<p style="width: 100%;"><el-radio :label="3">按顺序依次审批</el-radio></p>
								<p style="width: 100%;"><el-radio :label="1">会签 (可同时审批，每个人必须审批通过)</el-radio></p>
								<p style="width: 100%;"><el-radio :label="2">或签 (有一人审批通过即可)</el-radio></p>
							</el-radio-group>
						</el-form-item>

						

						<el-form-item v-if="form.refuse?.handler" label="审批被拒绝">
							<el-radio-group v-model="form.refuse.handler" class="ml-4">
								<el-radio label="TO_END" size="large">直接结束流程</el-radio>
								<el-radio label="TO_NODE" size="large">驳回到指定节点</el-radio>
							</el-radio-group>
							<el-select v-if="form.refuse.handler === 'TO_NODE'" v-model="form.refuse.nodeId"
								placeholder="驳回节点" style="width: 100%;margin-bottom: 20px;">
								<el-option v-for="item in rejectNodeList" :key="item.id" :label="item.name"
									:value="item.id" />
							</el-select>
						</el-form-item>
					</el-form>
				</el-main>
				<el-footer>
					<el-button type="primary" @click="save">保存</el-button>
					<el-button @click="drawer = false">取消</el-button>
				</el-footer>
			</el-container>
		</el-drawer>
	</div>
</template>

<script setup>
import addNode from './addNode.vue'
import sysApi from '@/api/model/system.js'
import { ref, onMounted, nextTick, computed,inject,watch } from 'vue'
import { ElNotification } from 'element-plus'
import { Warning } from '@element-plus/icons-vue'
import { flatFunc, getItemAncestors } from './utils/recursion.js'
import { checkApprover } from './utils/check.js'
import {setApproverStr} from './utils/toText.js'
const props = defineProps({
	modelValue: { type: Object, default: () => { } },
	currentNode: { type: Object, default: () => { } }
})
const emit = defineEmits(['update:modelValue'])
const nodeConfig = ref(JSON.parse(JSON.stringify(props.modelValue)))
watch(nodeConfig, (newValue) => {
    emit('update:modelValue',newValue)
}, {
    deep: true
})
const nodeList = inject('nodeList')
const dataList = inject('dataList')
const drawer = ref(false)
const isEditTitle = ref(false)
const form = ref({})
const nodeTitle = ref(null)
const deptFileName = ref('DeptReport')
const deptList = ref([])
const employeeFileName = ref('ChooseEmployeeReport')
const employeeList = ref([])
const employeeList2 = ref([])
const roleFileName = ref('OptRoleReport')
const roleList = ref([])
const apiObj = ref(sysApi.select.query)
const tableProps = {
	label: 'name',
	value: 'id',
}
const tableProps2 = {
    label: 'name',
    value: 'nodeId',
}
const formDeptList = computed(() => {
	return dataList.value.filter(res => res.type === 'SelectDept'|| res.type === 'SelectMultiDept');
})
const formUserList = computed(() => {
	return dataList.value.filter(res => res.type === 'SelectUser'|| res.type === 'SelectMultiUser');
})
const formDeptId= computed({
	get() {
		if(formDeptList.value.findIndex(res => res.id === form.value.formUserId) == -1){
			return 
		}
		else{
			return form.value.formDeptId;
		}
		
	},
	set(val) {
		form.value.formDeptId = val
		form.value.formDeptName = formDeptList.value.filter(res => res.id === val)[0].name
	}
})
const formUserId= computed({
	get() {
		if(formUserList.value.findIndex(res => res.id === form.value.formUserId) == -1){
			return 
		}
		else{
			return form.value.formUserId;
		}
	},
	set(val) {
		form.value.formUserId = val
		form.value.formUserName = formUserList.value.filter(res => res.id === val)[0].name
	}
})
const rejectNodeList = ref([])
onMounted(() => {
	console.log(props.modelValue.nodeUserList)
	props.modelValue.nodeUserList.forEach(ele => {
		if (ele.type == 'dept') {
			deptList.value.push(ele)
		}
		else if (ele.type == 'user') {
			employeeList.value.push(ele)
		}
		else if (ele.type == 'role') {
			roleList.value.push(ele)
		}
	})
	props.modelValue.nobody.assignedUser.forEach(item=>{
		employeeList2.value.push({ nodeId: item.id, name: item.name, nodeType: item.type })
	})
})
const show = () => {
	let arr = []
	flatFunc(arr, nodeList.value)
	getItemAncestors(rejectNodeList.value, arr, props.modelValue.parentId)
	form.value = JSON.parse(JSON.stringify(nodeConfig.value))
	drawer.value = true
}
const delNode = () => {
	if(nodeConfig.value.childNode){
		nodeConfig.value.childNode.parentId = nodeConfig.value.parentId
	}
	emit("update:modelValue", nodeConfig.value.childNode)
}
const editTitle = () => {
	isEditTitle.value = true
	nextTick(() => {
		nodeTitle.value.focus()
	})
}
const saveTitle = () => {
	isEditTitle.value = false
}
const typeChange = (val) => {

}
const delDept = (index) => {
	deptList.value.splice(index, 1)
}
const delEmployee = (index) => {
	employeeList.value.splice(index, 1)
}
const delRole = (index) => {
	roleList.value.splice(index, 1)
}
const save = () => {
	if (form.value.assignedType == 1) {
		form.value.nodeUserList = employeeList.value
	}
	else if (form.value.assignedType == 3) {
		form.value.nodeUserList = roleList.value
	}
	else if (form.value.assignedType == 9) {
		form.value.nodeUserList = deptList.value
	}
	if (checkApprover(form.value)!==false) {
		form.value.error = false
	}
	else{
		form.value.error = true
	}
	console.log(form.value)
	emit('update:modelValue', form.value)
}
const deptChange = (val) => {
	let arr = []
	val.map((item) => {
		arr.push({ id: item.id, name: item.name, type: "dept" })
	})
	deptList.value = arr
}
const employeeChange = (val) => {
	let arr = []
	val.map((item) => {
		arr.push({ id: item.id, name: item.name, type: "user" })
	})
	employeeList.value = arr
}
const employeeChange2 = (val) => {
	let arr = []
	val.map((item) => {
		arr.push({ id: item.id, name: item.name, type: "user" })
	})
	form.value.nobody.assignedUser = arr
}

const roleChange = (val) => {
	let arr = []
	val.map((item) => {
		arr.push({ id: item.id, name: item.name, type: "role" })
	})
	roleList.value = arr
}
const toText = (nodeConfig) => {
	nodeConfig.placeHolder = setApproverStr(nodeConfig)
	return nodeConfig.placeHolder
}

</script>

<style lang="less" scoped>
.formLabel {
	:deep(.el-form-item__label) {
		font-weight: bold;
		color: black;
		font-size: 16px;
	}
}
</style>
